from fastapi.routing import APIRouter


import sys
import os
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))

from fastapi import APIRouter, HTTPException, Query, UploadFile, File, Response, Form
from typing import List, Optional
from pydantic import BaseModel
from api.fault_service import FaultService
from models import (
    FaultRecord, FaultCreate, FaultUpdate, FaultStats, 
    ManufacturerStats, FaultTrend, AdvancedSearchRequest
)

router: APIRouter = APIRouter(prefix="/faults", tags=["faults"])

# 全局故障服务实例
fault_service = FaultService()

@router.post("/", response_model=FaultRecord)
async def create_fault(fault: FaultCreate):
    """创建故障记录 - HTTP接口层"""
    try:
        # 添加日志以调试接收到的数据
        print(f"接收到的故障数据: {fault}")
        return fault_service.create_fault(fault)
    except Exception as e:
        print(f"创建故障时发生错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/{fault_id}", response_model=FaultRecord)
async def get_fault(fault_id: int):
    """获取指定故障记录 - HTTP接口层"""
    fault = fault_service.get_fault_by_id(fault_id)
    if fault is None:
        raise HTTPException(status_code=404, detail="故障记录未找到")
    return fault

@router.get("/", response_model=dict)
async def list_faults(
    page: int = 1, 
    size: int = 6
):
    """获取故障记录列表 - HTTP接口层"""
    try:
        # 将page和size转换为skip和limit
        skip = (page - 1) * size
        limit = size
        
        # 获取故障记录（移除了search参数）
        faults = fault_service.get_faults(skip=skip, limit=limit)
        
        # 获取总记录数（移除了search参数）
        total_records = fault_service.get_faults_count()
        
        return {
            "faults": faults,
            "totalRecords": total_records,
            "currentPage": page,
            "totalPages": (total_records + size - 1) // size
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/advanced-search", response_model=dict)
async def advanced_search_faults(search_request: AdvancedSearchRequest):
    """高级搜索故障记录 - HTTP接口层"""
    try:
        # 将page和size转换为skip和limit
        skip = (search_request.page - 1) * search_request.size
        limit = search_request.size
        
        # 获取故障记录
        faults = fault_service.get_faults_advanced(
            skip=skip, 
            limit=limit, 
            factory_names=search_request.factory_names,
            host_names=search_request.host_names,
            alarm_names=search_request.alarm_names,
            start_date=search_request.start_date,
            end_date=search_request.end_date,
            status=search_request.status
        )
        
        # 获取总记录数
        total_records = fault_service.get_faults_count_advanced(
            factory_names=search_request.factory_names,
            host_names=search_request.host_names,
            alarm_names=search_request.alarm_names,
            start_date=search_request.start_date,
            end_date=search_request.end_date,
            status=search_request.status
        )
        
        return {
            "faults": faults,
            "totalRecords": total_records,
            "currentPage": search_request.page,
            "totalPages": (total_records + search_request.size - 1) // search_request.size
        }
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.put("/{fault_id}", response_model=FaultRecord)
async def update_fault(fault_id: int, fault_update: FaultUpdate):
    """更新故障记录 - HTTP接口层"""
    try:
        print(f"接收到更新请求，ID: {fault_id}, 数据: {fault_update}")
        fault = fault_service.update_fault(fault_id, fault_update)
        if fault is None:
            print(f"未找到ID为 {fault_id} 的记录")
            raise HTTPException(status_code=404, detail="故障记录未找到")
        print(f"更新成功，返回数据: {fault}")
        return fault
    except Exception as e:
        print(f"更新记录时发生错误: {e}")
        raise HTTPException(status_code=500, detail=str(e))

@router.delete("/{fault_id}")
async def delete_fault(fault_id: int):
    """删除故障记录 - HTTP接口层"""
    try:
        success = fault_service.delete_fault(fault_id)
        if not success:
            raise HTTPException(status_code=404, detail="故障记录未找到")
        return {"message": "故障记录删除成功"}
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/stats/summary", response_model=FaultStats)
async def get_fault_stats():
    """获取故障统计信息 - HTTP接口层"""
    try:
        return fault_service.get_fault_stats()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/stats/manufacturer", response_model=List[ManufacturerStats])
async def get_manufacturer_stats(
    start_date: Optional[str] = Query(None, description="开始日期 (YYYY-MM-DD)"),
    end_date: Optional[str] = Query(None, description="结束日期 (YYYY-MM-DD)")
):
    """获取厂家统计信息 - HTTP接口层"""
    try:
        return fault_service.get_manufacturer_stats(start_date, end_date)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/stats/trend", response_model=List[FaultTrend])
async def get_fault_trend(days: int = 7):
    """获取故障趋势 - HTTP接口层"""
    try:
        return fault_service.get_fault_trend(days)
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/export/csv", response_model=List[FaultRecord])
async def export_faults_csv():
    """导出故障记录为CSV格式 - HTTP接口层"""
    try:
        return fault_service.export_faults_csv()
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.get("/export/excel")
async def export_faults_excel():
    """导出故障记录为Excel格式 - HTTP接口层"""
    try:
        excel_data = fault_service.export_faults_excel()
        return Response(
            content=excel_data,
            media_type="application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
            headers={"Content-Disposition": "attachment; filename=fault_records.xlsx"}
        )
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))

@router.post("/import/excel")
async def import_faults_excel(
    file: UploadFile = File(...),
    hasHeader: bool = Form(default=True)
):
    """从Excel文件导入故障记录 - HTTP接口层"""
    try:
        # 检查文件类型
        if not file.filename.endswith(('.xlsx', '.xls', '.csv')):
            raise HTTPException(status_code=400, detail="只支持Excel文件 (.xlsx, .xls) 或 CSV文件 (.csv)")
        
        # 读取文件内容
        content = await file.read()
        
        if not content:
            raise HTTPException(status_code=400, detail="文件内容为空")
        
        # 导入数据
        success_count, error_count, error_details = fault_service.import_faults_from_excel(content, file.filename, hasHeader)
        
        # 构建返回消息
        message = f"导入完成！成功: {success_count}, 失败: {error_count}"
        
        # 如果有错误详情，添加到返回结果中
        if error_details:
            message += f"\n\n失败详情:\n"
            for error in error_details[:10]:  # 只显示前10个错误，避免消息过长
                message += f"第{error['row']}行: {error['error']} - {error['details']}\n"
            if len(error_details) > 10:
                message += f"... 还有{len(error_details) - 10}个错误未显示"
        
        return {
            "message": message,
            "success_count": success_count,
            "error_count": error_count,
            "error_details": error_details if error_details else None
        }
    except HTTPException:
        # 重新抛出HTTP异常
        raise
    except Exception as e:
        error_msg = str(e)
        print(f"导入Excel文件时发生错误: {error_msg}")
        raise HTTPException(status_code=500, detail=f"导入失败: {error_msg}")

class SQLQuery(BaseModel):
    """SQL查询模型"""
    query: str

@router.post("/execute-sql")
async def execute_sql_query(sql_query: SQLQuery):
    """执行SQL查询语句 - HTTP接口层"""
    try:
        result = fault_service.execute_sql(sql_query.query)
        return result
    except Exception as e:
        raise HTTPException(status_code=500, detail=str(e))